var ImgBox;
var ImgBoxPage = 'ImgBoxPage';
if(ImgBox == null){
	ImgBox = {};
	ImgBox.imgBox = null;
	ImgBox.imgBoxBody = null;
	
}

ImgBox.updatePosition = function() {
	var imgBox = ImgBox.imgBox;
	imgBox.css('z-index', '1');
	imgBox.css('position', 'fixed');
	imgBox.css('top', '0px');
	imgBox.css('left', '0px');
	imgBox.css('width', (parseInt($('body').css('width'))+0)+'px');
	imgBox.css('height', innerHeight+'px');
	imgBox.css('opacity', .4);
	imgBox.css('background-color', '#000');
	
	var imgBoxBody = ImgBox.imgBoxBody;
	var xOfseet = (parseInt(imgBox.css('width'))/100)*2;
	var yOfseet = (parseInt(innerHeight)/100)*4;
	var imgBoxBodyWidth = (parseInt(imgBox.css('width')) - 2 * xOfseet);
	var imgBoxBodyHeight = innerHeight - 2 * yOfseet;
	imgBoxBody.css('z-index', '2');
	imgBoxBody.css('position', 'fixed');
	imgBoxBody.css('left', xOfseet + 'px');
	imgBoxBody.css('top', yOfseet + 'px');
	imgBoxBody.css('width', imgBoxBodyWidth + 'px');
	imgBoxBody.css('height', imgBoxBodyHeight + 'px');
	imgBoxBody.css('background-color', '#fff');
	
	
	var height = (parseInt(innerHeight)/100)*80;
	imgBoxBody.find('img').css('height', height+'px')
	
	
	childsWidth = parseInt(ImgBox.imgBoxBody.find('.hidden').css('width')) + parseInt(ImgBox.imgBoxBody.find('img').css('width'));
	ImgBox.imgBoxBody.css('width', (childsWidth + 70) + 'px');
	xOfseet = (parseInt(imgBox.css('width')) - parseInt(imgBoxBody.css('width')))/2;
	imgBoxBody.css('left', xOfseet + 'px');
}
ImgBox.show = function() {
	if($('body').find('#ImgBox').length==0){
		$('body').append('<div id="ImgBox">');
		$('body').append('<div id="ImgBoxBody">');
		ImgBox.imgBoxBody = $('#ImgBoxBody');
		ImgBox.imgBox = $('#ImgBox');
		ImgBox.imgBox.click(ImgBox.hide);
		$( window ).resize(ImgBox.updatePosition);
	} else {
		ImgBox.imgBox.css('display', 'block')
		ImgBox.imgBoxBody.css('display', 'block')
	}
	ImgBox.updatePosition();
	
}
ImgBox.hide = function() {
	ImgBox.imgBox.css('display', 'none')
	ImgBox.imgBoxBody.css('display', 'none')
	ImgBox.stopListening();
}
ImgBox.isAdmin = false;
ImgBox.datas = new Array();
ImgBox.open2 = function(id, datas, isAdmin) {
	ImgBox.isAdmin = isAdmin;
	var itemData;
	console.log("ImgBox.open2");
	var index;
	ImgBox.datas = datas;
	for (var i=0; i < datas.length; i++){
		if(datas[i].id==id){
			itemData = datas[i];
			index = i;
			break;
		}
	}
	console.log("index: " + index);
	console.log(itemData);
	ImgBox.show();
	ImgBox.imgBoxBody.html("");
		var content = "";
		if(itemData.name){
			content += "<b>Название: </b> " + itemData.name + "</br>";
		}
		if(itemData.description && itemData.description != ""){
			content += itemData.description + "</br>";
		}
		if(itemData.cost && itemData.cost != 0 && itemData.cost != "0" && itemData.cost != ""){
			content += "<b>Стоимость: </b> " + itemData.cost + "</br>";
		}
		if(itemData.cost_for_hire && itemData.cost_for_hire != 0 && itemData.cost_for_hire != "0" && itemData.cost_for_hire != ""){
			content += "<b>Стоимость: </b> " + itemData.cost_for_hire + "</br>";
		}
		var imgContent = "<div class='img_body' style='float: left; padding: 30px;'>";
		imgContent += "<img src='"+itemData.img+"' style='height: 556px;' /></br>";
		imgContent += "<a href='javascript:' class='navBtn'id='prevBtn' title='предыдущий товар. Так же можно использовать стрелки клавиатуры'> <<< </a>";
		imgContent += "<a href='javascript:' class='navBtn' id='nextBtn' title='следующий товар. Так же можно использовать стрелки клавиатуры'> >>> </a>";
		imgContent += "</div>";
		ImgBox.imgBoxBody.append(imgContent);
	var imgLoad = $("<img />");
	imgLoad.attr("src", itemData.img);
	imgLoad.unbind("load");
	imgLoad.unbind("error");
	imgLoad.bind('error', function () {
		var msg = "Sorry but there was an error: ";
		addAminTools(id, index, isAdmin);
	});
	imgLoad.bind("load", function () {
		if ( status == "error" ) {
			var msg = "Sorry but there was an error: ";
			alert( msg + xhr.status + " " + xhr.statusText );
			return;
		  }
		ImgBox.imgBoxBody.append("<div class='hidden' style='padding-top:40px;float:left;display:none;width:400px;height:300px;'>" +  content + "</div>");
		unselectElement(".img_body");
		useHandCursor('.navBtn');
		if(index>0){
			$('#prevBtn').click(function(){
				ImgBox.open2(ImgBox.datas[--index].id, ImgBox.datas, isAdmin);
			});
		} else {
			$('#prevBtn').addClass('dis');
			useDefaultCursor('#prevBtn');
		}
		if(index<ImgBox.datas.length-1){
			$('#nextBtn').click(function(){
				ImgBox.open2(ImgBox.datas[++index].id, ImgBox.datas, isAdmin);
			});
		} else {
			$('#nextBtn').addClass('dis');
			useDefaultCursor('#nextBtn');
		}
		addAminTools(id, index, isAdmin);
		
		ImgBox.imgBoxBody.find('.must_hidden').css('display', 'none')
		ImgBox.imgBoxBody.find('.hidden').css('display', 'block')
		ImgBox.updatePosition();
	});
	ImgBox.startListening(index);
	/*$("#ImgBox").keypress(function( event ){
	  console.log(event);
	  if ( event.which == 13 ) {
		 event.preventDefault();
	  }
	  xTriggered++;
	  var msg = "Handler for .keypress() called " + xTriggered + " time(s).";
	  $.print( msg, "html" );
	  $.print( event );
	});*/
}
function addAminTools(id, index, isAdmin){
	if(isAdmin){
		console.log("id: " + id);
		ImgBox.imgBoxBody.append("<button id='edite'>Edite</button>");
		ImgBox.imgBoxBody.append("<button id='delete'>Delete</button>");
		$('#delete').click(function(){
			query("admin&action=delete_item&item="+id+"&uid=" + UserData.uid, function(data) {
				if(typeof data == 'string'){
					data = JSON.parse(data);
				}
				ImgBox.datas.remove(index);
				ImgBox.open2(ImgBox.datas[index].id, ImgBox.datas, isAdmin);
			});
		});
		$('#edite').click(function(){
			query("admin&action=edit_item&item="+id+"&uid=" + UserData.uid, function(data) {
				if(typeof data == 'string'){
					data = JSON.parse(data);
				}
				HtmlBox.open(data.content, function(){
					
					query("product_items&action=get_item&item="+id, function(data) {
						console.log("item data: ");
						console.log(data);
						ImgBox.datas[index] = data[0];
						ImgBox.open2(ImgBox.datas[index].id, ImgBox.datas, isAdmin);
					});
				});
				ImgBox.stopListening();
			});
		});
	}
}
ImgBox.stopListening = function(index) {
	window.onkeyup = null;
}
ImgBox.startListening = function(index) {
	isAdmin = ImgBox.isAdmin
	window.onkeyup = function(e) {
		var key = e.keyCode ? e.keyCode : e.which;
		switch(key){
			case 27:
				ImgBox.hide();
				break;
			case 39:
				if(index<ImgBox.datas.length-1){
					ImgBox.open2(ImgBox.datas[++index].id, ImgBox.datas, isAdmin);
				}
				break;
			case 37:
				if(index>0){
					ImgBox.open2(ImgBox.datas[--index].id, ImgBox.datas, isAdmin);
				}
				break;
		}
	}
}
ImgBox.open = function(jqSelector) {
	ImgBox.show();
	console.log($(this));
	console.log($(this).find('img').attr('src'));
	console.log($(this).html());
	ImgBox.imgBoxBody.html($(this).html());
	ImgBox.imgBoxBody.find('.must_hidden').css('display', 'none')
	ImgBox.imgBoxBody.find('.hidden').css('display', 'block')
	ImgBox.updatePosition();
}
var btnId = 0;
var imgId = 0;
function addBtn(item) {
	$('#img_box_con').append(
		"<div id='imgBtn"+(++btnId)+"' class='img_btn shadowed' style='height:130px;'>"+
			"<img src='" + item.img + "' alt='"+item.description + "' /><br />"+
		"</div>"
	);
	return "imgBtn"+btnId;
}

function addImgBox(item){
	$('#img_box_con').append(
		"<div id='img"+(++imgId)+"' class='img_box_info'>"+
			"<div class='img_box'>"+
				"<img src='" + item.img + "' title='"+item.name + "' /><br />"+
			"</div>"+
			"<div class='hidden' style='float:left;display:none;width:400px;height:300px;'>" +  item.description + "</div>"+
			"<marquee class='must_hidden' scrollamount='0' style='width:100px;height:30px;'>" +  item.name + "</marquee>"+
		"</div>"
	);
	var resultId = "img"+imgId;
	unselectElement('#'+resultId);
	var img_box = $('#'+resultId);
	var img = img_box.find('img');
	var imgLoader = new Image();
	
	imgLoader.onload = function () {
		var _imgLoader = this;
		
		
		
		
		var marginTop = (100-parseInt(img.css('height')))/2;
		var marginLeft = (105-parseInt(img.css('width')))/2;
		
		
		img.css('margin-top', (marginTop)+'px');
		img.css('margin-left', (marginLeft)+'px');
		
		img.hover(function(){
			var imgBoxInfOnOverCss = {
				zIndex:100, width:170, height:170, maxWidth:170, maxHeight:170, marginTop:-20, marginLeft:-10, marginBottom:0, marginRight:-10
			}
			var imgBoxInfOnOutCss = {
				
				width:150, height:150, maxWidth:110, maxHeight:130, marginTop:20, marginLeft:20, marginBottom:20, marginRight:20
			}
			img.unbind('mouseout');
			img.mouseout(function() {
				img.unbind('mousemove');
				img.parent().stop();
				img.stop();
				// console.log("marginTop: "+marginTop)
				// console.log("marginLeft: "+marginLeft)
				var marginTop = (100-parseInt(img.css('height')))/2;
				var marginLeft = (105-parseInt(img.css('width')))/2;
				
				img.parent().animate({width:105, height:100, marginTop:0, marginLeft:0}, 200, function() {});
				img.animate({minHeight:100, maxHeight:155,marginTop:marginTop, marginLeft:marginLeft}, 400, function() {});
			});
			
			
			img.parent().stop();
			img.stop();
			
			
			img.parent().animate({width:120, height:140, marginTop:-7, marginLeft:-7}, 200, function() {});
			var cssObj = {};
			if(_imgLoader.width>_imgLoader.height){
				cssObj.height=140;
				cssObj.minWidth='none';
				cssObj.marginLeft=-((_imgLoader.width/_imgLoader.height)*cssObj.height - 140)/2;
				cssObj.marginTop=0;
				
			} else if(_imgLoader.width<_imgLoader.height) {
				cssObj.width=120;
				cssObj.minHeight='none';
				cssObj.marginTop= 0;
				cssObj.marginLeft=0;
				
			} else {
				cssObj.height=140;
				cssObj.width=120;
				cssObj.marginTop=0;
				cssObj.marginLeft=0;
				
			}
			var animId = 0;
			img.animate(cssObj, 200, function() {
				img.mousemove(function( event ) {
					if(_imgLoader.width>_imgLoader.height){
						var imgW = (_imgLoader.width/_imgLoader.height)*140;
						var parentImgW = 120;
						var ml = -(imgW - parentImgW)*(event.layerX/parentImgW);
						img.css("margin-left", ml+'px');
						//console.log( imgW +' _ '+ parentImgW+' _ '+event.layerX+' _ '+ml) 
					} else {
						var imgH = (_imgLoader.width/_imgLoader.height)*120;
						var parentImgH = 140;
						var mr = -(imgH - parentImgH)*(event.layerH/parentImgH);
						
						
						img.css("margin-top", mr+'px');
					}
				});
			});
			
		});
	}
	imgLoader.src = item.img;
	return resultId;
}